<?php

namespace app\load\service;

use app\load\loadModel\AdminModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

/**
 * 员工服务层
 */
class AdminService
{


    /**
     * 登录
     * @param $username |账号
     * @param $password |密码
     * @return string
     * @throws Exception
     */
    public function login($username, $password): string
    {

        $UserModel = AdminModel::Admin();

        $user_info = $UserModel->where('username|mobile', $username)->find();
        if (empty($user_info)) {
            throw new Exception('账号或密码错误');
        }
        $password = set_password($password, $user_info['salt']);
        if ($password != $user_info['pwd']) {
            throw new Exception('账号或密码错误');
        }
        if ($user_info['status'] == -1) {
            throw new Exception('该员工禁止登录，请联系平台');
        }

        $res = $UserModel->removeOption()->where('id', $user_info['id'])->update([
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
            'login_num' => $user_info['login_num'] + 1,
        ]);

        $token = '';
        if ($res) {
            $token = getToken($user_info['id']);
        }
        return $token;
    }

    /**
     * 员工详情
     * @param $where | 条件
     * @param string $filed | 字段
     * @return array|object
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function info($where , string $filed ='*')
    {

        return AdminModel::Admin()->where($where)
            ->field($filed)->filter(function ($admin){
                $admin['dep_name'] = AdminModel::Department()->where('id' , $admin['did'])->value('title');
                $admin['position_name'] = AdminModel::Position()->where('id' , $admin['did'])->value('title');
                $admin['thumb'] = env('url') . $admin['thumb'];
            })
            ->find();
    }


    /**
     * 部门员工
     * @param array $where
     * @param string $filed
     * @return null|array|object
     */
    public function departmentUserList(array $where = [] , string $filed = 'a.id,a.did,a.position_id,a.mobile,a.name,a.nickname,a.sex,a.status,a.thumb,a.username,d.title as department'){
      return  AdminModel::Admin()->departmentUserList($where,$filed);
    }

    /**
     * 修改用户信息
     * @param array $where
     * @param array $data
     * @return \app\adm\model\AdminModel
     */
    public function save(array $where, array $data)
    {
        return AdminModel::Admin()->where($where)->update($data);
    }


}